﻿//opening time and site message
var OpeningTimesAndSiteMessage = function () {
    var openingHours = {};
    var openingHoursChanged = false;
    var siteMessages = [];
    var emergencyMessage = "";
    var emergencyMessageChanged = false;

    var Decode = function (str) {
        str = str.replace(/&quot;/ig, "\"");
        return str;
    };

    var Encode = function (str) {
        //encode the &'s so that they dont mess up the form values
        str = str.replace(/&/ig, "U0026");
        //get rid of newlines and multiple spaces
        str = str.replace(/( ( +))|(\r)|(\n)/ig, "");
        return str;
    };

    var getData = function () {
        $.ajax({
            type: "GET",
            url: "/intranet/GetDataOpeningTimesAndSiteMessages",
            success: function (data, textStatus) {
                var rtnObj = eval(data)[0];
                openingHours = rtnObj.OpeningHours;
                siteMessages = rtnObj.SiteMessages;
                emergencyMessage = Decode(rtnObj.EmergencyMessage);

                drawOpeningTimes();
                drawSiteMessages();
                drawEmergencyMessage();
            },
            error: function (ajaxObj, textStatus, errorThrown) {
                alert(ajaxObj.responseText);
            }
        });
    };

    var addEditableInputType = function () {
        $.editable.addInputType("textarea", {
            element: function (settings, original) {
                var textarea = $('<textarea>');
                if (settings.rows) {
                    textarea.attr('rows', settings.rows);
                } else {
                    textarea.height(settings.height);
                }
                if (settings.cols) {
                    textarea.attr('cols', settings.cols);
                } else {
                    textarea.width(settings.width);
                }
                $(this).append(textarea);
                return (textarea);
            }
        });
    };

    var drawOpeningTimes = function () {
        //set up a table
        var table = document.createElement("table");
        $(table).attr("cellpadding", "0");
        $(table).attr("cellspacing", "0");
        $("#opening-times").append(table);
        var thead = document.createElement("thead");
        $(table).append(thead);
        var row = thead.insertRow(-1);
        $(row).addClass("head-row");
        //put the head row in...
        $(row).html("<th></th><th>Sales Hours</th><th></th><th>Care Hours</th><th></th>");
        row = thead.insertRow(-1);
        //...and the column headers
        $(row).html("<th>Day</th><th>Opening Time</th><th>Closing Time</th><th>Opening Time</th><th>Closing Time</th>");
        var tbody = document.createElement("tbody");
        $(table).append(tbody);
        //set up a little array of daynames in the order we want them
        var dayNames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
        //loop through the days and get the times for each department
        var sales = openingHours.Sales;
        var care = openingHours.Care;
        for (var idx = 0; idx < dayNames.length; idx++) {
            var day = dayNames[idx];
            var curDaySales = sales[day];
            var curDayCare = care[day];
            row = tbody.insertRow(-1);
            $(row).attr("rel", day);
            $(row).html("<td class=\"day-name\">" + day +
                "</td><td class=\"time\" rel=\"sales-open\">" + curDaySales.OpeningTime + "</td><td class=\"time\" rel=\"sales-close\">" + curDaySales.ClosingTime +
                "</td><td class=\"time\" rel=\"care-open\">" + curDayCare.OpeningTime + "</td><td class=\"time\" rel=\"care-close\">" + curDayCare.ClosingTime + "</td>");
        }
        //set up the "time" fields to be editable
        $(".time").editable(function (value, settings) {
            $("#save-opening-times").removeAttr("disabled");
            return value;
        }, {
            submit: 'OK',
            cancel: 'Cancel',
            tooltip: "Click to edit.",
            onblur: "ignore",
            width: "40px"
        });
        $("#save-opening-times").click(function () {
            //get the tbody element
            var tbody = $("#opening-times tbody")[0];
            //step through the rows and build up some data for the request
            var data = "";
            //sales
            var moso = $(tbody).find("tr[rel=Monday]").find("td[rel=sales-open]").html();
            var mosc = $(tbody).find("tr[rel=Monday]").find("td[rel=sales-close]").html();
            var tuso = $(tbody).find("tr[rel=Tuesday]").find("td[rel=sales-open]").html();
            var tusc = $(tbody).find("tr[rel=Tuesday]").find("td[rel=sales-close]").html();
            var weso = $(tbody).find("tr[rel=Wednesday]").find("td[rel=sales-open]").html();
            var wesc = $(tbody).find("tr[rel=Wednesday]").find("td[rel=sales-close]").html();
            var thso = $(tbody).find("tr[rel=Thursday]").find("td[rel=sales-open]").html();
            var thsc = $(tbody).find("tr[rel=Thursday]").find("td[rel=sales-close]").html();
            var frso = $(tbody).find("tr[rel=Friday]").find("td[rel=sales-open]").html();
            var frsc = $(tbody).find("tr[rel=Friday]").find("td[rel=sales-close]").html();
            var saso = $(tbody).find("tr[rel=Saturday]").find("td[rel=sales-open]").html();
            var sasc = $(tbody).find("tr[rel=Saturday]").find("td[rel=sales-close]").html();
            var suso = $(tbody).find("tr[rel=Sunday]").find("td[rel=sales-open]").html();
            var susc = $(tbody).find("tr[rel=Sunday]").find("td[rel=sales-close]").html();
            data += "moso=" + moso + "&mosc=" + mosc + "&tuso=" + tuso + "&tusc=" + tusc + "&weso=" + weso + "&wesc=" + wesc +
                "&thso=" + thso + "&thsc=" + thsc + "&frso=" + frso + "&frsc=" + frsc + "&saso=" + saso + "&sasc=" + sasc +
                "&suso=" + suso + "&susc=" + susc;
            //care
            var moco = $(tbody).find("tr[rel=Monday]").find("td[rel=care-open]").html();
            var mocc = $(tbody).find("tr[rel=Monday]").find("td[rel=care-close]").html();
            var tuco = $(tbody).find("tr[rel=Tuesday]").find("td[rel=care-open]").html();
            var tucc = $(tbody).find("tr[rel=Tuesday]").find("td[rel=care-close]").html();
            var weco = $(tbody).find("tr[rel=Wednesday]").find("td[rel=care-open]").html();
            var wecc = $(tbody).find("tr[rel=Wednesday]").find("td[rel=care-close]").html();
            var thco = $(tbody).find("tr[rel=Thursday]").find("td[rel=care-open]").html();
            var thcc = $(tbody).find("tr[rel=Thursday]").find("td[rel=care-close]").html();
            var frco = $(tbody).find("tr[rel=Friday]").find("td[rel=care-open]").html();
            var frcc = $(tbody).find("tr[rel=Friday]").find("td[rel=care-close]").html();
            var saco = $(tbody).find("tr[rel=Saturday]").find("td[rel=care-open]").html();
            var sacc = $(tbody).find("tr[rel=Saturday]").find("td[rel=care-close]").html();
            var suco = $(tbody).find("tr[rel=Sunday]").find("td[rel=care-open]").html();
            var succ = $(tbody).find("tr[rel=Sunday]").find("td[rel=care-close]").html();
            data += "&moco=" + moco + "&mocc=" + mocc + "&tuco=" + tuco + "&tucc=" + tucc + "&weco=" + weco + "&wecc=" + wecc +
                "&thco=" + thco + "&thcc=" + thcc + "&frco=" + frco + "&frcc=" + frcc + "&saco=" + saco + "&sacc=" + sacc +
                "&suco=" + suco + "&succ=" + succ + "&newtable=" + $("#opening-times").html();
            //then send this data to the ajax page!
            $.ajax({
                type: "POST",
                url: "/intranet/SetOpeningTimes",
                data: data,
                cache: false,
                success: function (data, textStatus) {
                    alert("Success");
                },
                error: function (ajaxObj, textStatus, errorThrown) {
                    $("#debug-box").html(ajaxObj.responseText);
                }
            });
        });
    };

    var drawSiteMessages = function () {
        //create a list to hold the sites
        var siteList = document.createElement("ul");
        $("#site-messages").append(siteList);
        //for each site, create a new li
        for (var idx = 0; idx < siteMessages.length; idx++) {
            var site = siteMessages[idx];
            var li = document.createElement("li");
            $(li).attr("class", "site");
            $(li).attr("rel", site.StoreID);
            $(siteList).append(li);
            //and fill it with the data
            $(li).append("<h4>" + site.StoreName + "</h4>");
            var displayBox = document.createElement("input");
            $(displayBox).attr("type", "checkbox");
            $(displayBox).attr("id", site.StoreID + "-display");
            $(displayBox).attr("class", "display-toggle");
            $(displayBox).attr("rel", site.StoreID);
            $(displayBox).attr("checked", site.Display);
            $(li).append(displayBox);
            var messageContainer = document.createElement("div");
            $(messageContainer).attr("class", "site-message-content");
            $(messageContainer).attr("rel", site.StoreID);
            $(li).append(messageContainer);
            var message = Decode(site.Message);
            $(messageContainer).html(message);
            var submitBtn = document.createElement("input");
            $(submitBtn).attr("type", "button");
            $(submitBtn).attr("class", "submit-button btn btn-primary");
            $(submitBtn).attr("rel", site.StoreID);
            $(submitBtn).attr("ref", site.StoreName);
            $(submitBtn).attr("value", "Save Changes");
            $(submitBtn).attr("disabled", true);
            $(li).append(submitBtn);
        }
        $(".site-message-content").editable(function (value, settings) {
            //enable the submit button
            var siteID = $(this).attr("rel");
            $(".submit-button[rel=" + siteID + "]").removeAttr("disabled");
            return value;
        }, {
            type: "textarea",
            submit: 'OK',
            cancel: 'Cancel',
            tooltip: "Click to edit.",
            onblur: "ignore",
            height: "120px",
            width: "600px"
        });
        $("#site-messages .submit-button").click(function () {
            //get the values
            var siteID = $(this).attr("rel");
            var siteName = $(this).attr("ref");
            var display = $("#" + siteID + "-display").is(":checked");
            var message = $(".site-message-content[rel=" + siteID + "]").html();
            //encode the message for transit
            message = Encode(message);
            //check if the message is "empty" and make sure it is
            if (message == "Click to edit") message = "";
            if (confirm("Are you sure you want to save your changes to the " + siteName + " Site Message?")) {
                $.ajax({
                    type: "POST",
                    url: "/intranet/SetSiteMessage",
                    data: "storeId=" + siteID + "&display=" + display + "&message=" + message,
                    cache: false,
                    success: function (data, textStatus) {
                        alert("Success");
                    },
                    error: function (ajaxObj, textStatus, errorThrown) {
                        $("#debug-box").html(ajaxObj.responseText);
                    }
                });
            }
        });
        $("#site-messages .display-toggle").click(function () {
            //enable the submit button
            var siteID = $(this).attr("rel");
            $(".submit-button[rel=" + siteID + "]").removeAttr("disabled");
        });
    };

    var drawEmergencyMessage = function () {
        $("#emergency-site-message").html(emergencyMessage);
        //make the text editable
        $("#emergency-site-message").editable(function (value, settings) {
            $("#save-emergency-site-message").removeAttr("disabled");
            return value;
        }, {
            type: "textarea",
            submit: 'OK',
            cancel: 'Cancel',
            tooltip: "Click to edit.",
            onblur: "ignore",
            height: "120px",
            width: "600px"
        });
        $("#save-emergency-site-message").click(function () {
            //get the content from the container
            var message = $("#emergency-site-message").html();
            //encode the message for transit
            message = Encode(message);
            //check if the message is "empty" and make sure it is
            if (message == "Click to edit") message = "";
            if (confirm("Are you sure you want to save your changes to the Emergency Site Message?")) {
                $.ajax({
                    type: "POST",
                    url: "/intranet/SetEmergencyMessage",
                    data: "message=" + message,
                    cache: false,
                    success: function (data, textStatus) {
                        alert("Success");
                    },
                    error: function (ajaxObj, textStatus, errorThrown) {
                        $("#debug-box").html(ajaxObj.responseText);
                    }
                });
            }
        });
    };

    return {
        //main function to initiate the theme
        init: function () {
            addEditableInputType();
            getData();
        }
    };
}();

var FrontPageManagementV2 = function () {
    var endFunction = null;
    var currentCategoryID = 0;
    // When user select a new product option
    var SelectedNewProductOption = function () {
        $("#newProductOption").html(SelectedProductOptionName());
        //LoadingOn();
        $("#EditNewProduct h3").html(SelectedProductOptionName());
        $("#newProductOption").attr("value", SelectedProductOptionID());
        $("#newProductOption").attr("href", "/public/hieu/UserControls/ProductInfo.aspx?productID=" + $("#SelectedOptionInfo #hdProductId").val());
        $.ajax({
            type: "GET",
            url: "/intranet/productinfo",
            data: "productid=" + $("#SelectedOptionInfo #hdProductId").val() + "&ProductOptionID=" + SelectedProductOptionID() + "&requestType=DetailForFrontPage",
            success: function (msg) {
                $("#EditNewProduct .product .EditNewProductImage").attr("src", msg.Image);
                $("#EditNewProduct .product .prod-price").html("NOW £" + msg.Price);
                $("#EditNewProduct .product .prod-delivery").html("Delivery " + msg.DeliveryOptions + " Working Days*");
            }
        });
        endFunction = null;
        //LoadingOff();
    }

    // Save a change on a field of Product Option
    var SaveOptionChanges = function (frontPageOptionID, optionID, title, description) {
        $.ajax({
            type: "GET",
            url: "/intranet/SaveOptionFields",
            data: "frontPageOptionID=" + frontPageOptionID +
                    "&OptionID=" + optionID +
                    "&Title=" + encodeURIComponent(title) +
                    "&Description=" + encodeURIComponent(description),
            success: function (msg) {
            }
        });
    }
    
    // When user want to open the form to add a new product option
    var OpenFormAddNewProductToCategory = function (categoryID) {
        currentCategoryID = categoryID;
        var categoryName = $(".front-page-content #" + categoryID + " h2").html();
        $("#NewFrontPageItemForm #addProductToCategory").attr("value", "Add Product To " + categoryName.trim());
        DisplayForm("#NewFrontPageItemForm");
    }
    // Delete function for product option
    var DeleteOption = function (optionID) {
        $.ajax({
            type: "GET",
            url: "/intranet/DeleteFrontPageProductOption",
            data: "frontPageOptionID=" + optionID,
            beforeSend: function () {
                if (!confirm("Are you sure you want to delete this option?")) {
                    window.location.reload(true);
                    return false;
                }
            },
            success: function (msg) {
                alert("Delete successfully");
                $("#option-" + optionID).animate({ opacity: 0 }, 500, function () {
                    $("#option-" + optionID).remove();
                });
            }
        });
    }
    // Rearrange categories
    var ReArrangeCategories = function () {
        var thisContainer = $(".front-page-content");
        if ($(thisContainer).hasClass("ui-sortable")) {
            $(".RearrangeCategoriesButton").html("<img src='/img/intranet/page_component.gif'> Re-arrange Categories");
            $(thisContainer).sortable("destroy");
            $(thisContainer).enableSelection();
            var listPosition = "";
            $($(thisContainer).find(".frontPageCategory")).each(function () {
                listPosition += $(this).attr("id") + ",";
            });
            $.ajax({
                type: "GET",
                url: "/intranet/UpdateCategoryPositions",
                data: "CateogoryList=" + listPosition,
                beforeSend: function () {
                    if (!confirm("Are you sure you want to save the new order?")) {
                        window.location.reload(true);
                        return false;
                    }
                },
                success: function (msg) {
                    alert("Updated successfully");
                },
                error: function (rtnObj, message, errorThrown) {
                    $("#ajax-error").html(rtnObj.responseText);
                    alert(message + "\n\n" + errorThrown);
                }
            });
        }
        else {
            $(".RearrangeCategoriesButton").html("<img src='/img/intranet/page_component.gif'>  Finish arrange");
            $(thisContainer).sortable({ items: ".frontPageCategory" });
            $(thisContainer).disableSelection();
        }
    }
    // Rearrange options
    var ReArrangeOptions = function (categoryID) {
        var thisCat = $("#" + categoryID);
        if ($(thisCat).hasClass("ui-sortable")) {
            // Change the button and not allow to move the button anymore
            $(thisCat).find(".RearrangeOptionButton").html("<img src='/img/intranet/page_component.gif'> Re-arrange");
            $(thisCat).sortable("destroy");
            $(thisCat).enableSelection();
            var listPosition = "";
            $($(thisCat).find(".product")).each(function () {
                listPosition += $(this).attr("id").replace("option-", "") + ",";
            });
            $.ajax({
                type: "GET",
                url: "/intranet/UpdateOptionPosition",
                data: "OptionList=" + listPosition,
                beforeSend: function () {
                    if (!confirm("Are you sure you want to save the new order?")) {
                        return false;
                    }
                    //LoadingOn();
                },
                success: function (msg) {
                    alert("Updated successfully");
                    //LoadingOff();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        } else {
            // Change the button text and allow user move the control arround
            $(thisCat).find(".RearrangeOptionButton").html("<img src='/img/intranet/page_component.gif'>  Finish arrange");
            $(thisCat).sortable({ items: ".product" });
            $(thisCat).disableSelection();
        }
    }
    // Save a change on a field of category
    var SaveCategoryChanges = function (frontPageCategoryID, name, description) {
        $.ajax({
            type: "GET",
            url: "/intranet/SaveCategoryFields",
            data: "frontPageCategoryID=" + frontPageCategoryID +
                    "&Name=" + encodeURIComponent(name) +
                    "&Description=" + encodeURIComponent(description),
            success: function (msg) {
            }
        });
    }
    // Delete a category
    var DeleteCategory = function (frontPageCategoryID) {
        $.ajax({
            type: "GET",
            url: "/intranet/DeleteFrontPageCategory",
            data: "frontPageCategoryID=" + frontPageCategoryID,
            beforeSend: function () {
                if (!confirm("Are you sure you want to delete this category?")) {
                    return false;
                }
            },
            success: function (msg) {
                alert("Delete successfully");
                $("#" + frontPageCategoryID + ",.categoryBarControl[data-id='" + frontPageCategoryID + "']").animate({ opacity: 0 }, 500, function () {
                    $("#" + frontPageCategoryID + ",.categoryBarControl[data-id='" + frontPageCategoryID + "']").remove();
                });
            }
        });
    }
    // Function to hide and display form
    var DisplayForm = function (selector) {
        var thisForm = $(selector);
        $(thisForm).css("left", (($(window).width() - $(thisForm).outerWidth()) / 2) + "px");
        $(thisForm).css("top", (-1 * ($(thisForm).outerHeight() + 50)) + "px");
        var posibleTop = ($(window).height() - $(thisForm).height()) / 2;
        if (posibleTop < 0) posibleTop = 0;
        $(thisForm).animate({ top: ($(window).scrollTop() + posibleTop) }, 500);
    }
    var HideForm = function (selector) {
        var thisForm = $(selector);
        $(thisForm).animate({ left: (-1 * ($(thisForm).outerWidth() + 50)) }, 500);
    }
    var InitForm = function (selector) {
        var thisForm = $(selector);
        $(thisForm).css("position", "absolute");
        $(thisForm).css("left", "-999px");
        $(thisForm).css("top", "-999px");
    }
    function ajaxObject(param) {
        this.param = param;
        this.ajaxRequest = null;
        try {
            // Opera 8.0+, Firefox, Safari
            this.ajaxRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                this.ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    this.ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("Your browser does not support Ajax!");
                    return false;
                }
            }
        }
        // use response to get the response text
        this.response = function () {
            if (this.ajaxRequest.readyState == 4) {
                //return this.ajaxRequest.responseText;
                if (this.ajaxRequest.status == 200) {
                    return this.ajaxRequest.responseText;
                }
                else {
                    return this.ajaxRequest.status;
                }
            }
        }
        this.ajaxRequest.onreadystatechange = function () { this.response };
        this.ajaxRequest.open('GET', this.param, false);
        this.ajaxRequest.send(null);
    }
    
    var SelectedProductOptionName=function () {
        return $("#SelectedOptionInfo #SelectedOption").html();
    }
    
   var  SelectedProductOptionID=function () {
        return $("#SelectedOptionInfo #hdProductOptionId").val();
    }
    return {
        //main function to initiate the theme
        init: function() {
        // When user want to select a product option when creating a new front page item
        $("#SelectNewProductOption").click(function (e) {
            DisplayForm("#ProductOptionSearchDiv");
            endFunction = SelectedNewProductOption;
            e.preventDefault();
        });
        // Close the search product option form
        $("#CloseForProductOptionSearchButton").click(function () {
            HideForm("#ProductOptionSearchDiv");
        });
        // Close the search product option form and run the end function
        $("#OkForProductOptionSearchButton").click(function () {
            $("#CloseForProductOptionSearchButton").click();
            if ($.isFunction(endFunction)) {
                endFunction();
            }
        });
        $("#closeAddProduct2CatForm").click(function () {
            HideForm("#NewFrontPageItemForm");
        });
        // When user click on add a new front page category
        $("#NewFrontPageCategoryForm #addCategoryButton").click(function () {
            // Get the new information
            var newCatTitle = $("#NewFrontPageCategoryForm #categoryTitleText").val();
            var newCatInfo = $("#NewFrontPageCategoryForm #categoryInfoText").val();
            var newPostion = $(".front-page-content .frontPageCategory").length;
            var newStore = $(".WebsiteSelect").val();
            // Validation
            if (newCatTitle.length < 4) {
                alert("The title need to have at least 4 characters");
            } else {
                // Send the ajax to create new category
                $.ajax({
                    type: "GET",
                    url: "/intranet/NewFrontPageCategory",
                    data: "title=" + newCatTitle
                        + "&info=" + newCatInfo
                        + "&position=" + newPostion
                        + "&storeid=" + newStore,
                    success: function (msg) {
                        // if complete check the return message and add new category into the list
                        if (msg != "-1") {
                            $(".front-page-content").append(
                                "<div id='" + msg + "' class='frontPageCategory'>" +
                                    "<h2>" + newCatTitle + "</h2>" +
                                    "<p class='cat-info'>" + newCatInfo + "</p>" +
                                    "<div class='product'>" +
                                    "</div>" +
                                "</div>" +
                                "<div class='categoryBarControl'  data-id='" + msg + "'> " +
                                    "<a class='RearrangeOptionButton' onclick='FrontPageManagementV2.ReArrangeOptions(" + msg + ")'><img src='/img/intranet/page_component.gif'> Re-arrange</a>" +
                                    "<a class='NewOptionButton' onclick='FrontPageManagementV2.OpenFormAddNewProductToCategory(" + msg + ")'><img src='/img/intranet/page_new.gif'> Add option</a>" +
                                    "<a class='DeleteCatButton' onclick='FrontPageManagementV2.DeleteCategory(" + msg + ")'><img src='/img/intranet/folder_delete.gif'> Delete category</a>" +
                                "</div>" +
                                "<div class='clear-bottom'></div>"
                            );
                            // Assign editable for all category objects
                            $(".front-page-content #" + msg + " h2").editable(function (value, settings) {
                                SaveCategoryChanges($(this).parent().attr("id"), value, "");
                                return value;
                            }, {
                                submit: "Ok", cancel: "Cancel"
                            });
                            $(".front-page-content #" + msg + " .cat-info").editable(function (value, settings) {
                                SaveCategoryChanges($(this).parent().attr("id"), "", value);
                                return value;
                            }, {
                                submit: "Ok", cancel: "Cancel"
                            });

                            alert("New category \"" + newCatTitle + "\"added successfully");
                        } else {
                            alert("Failed to create a new category");
                        }
                        //make sure the controls are showing            
                        $(".categoryBarControl").show();
                        $("#NewFrontPageCategoryForm").show();
                    }
                });
            }
        });
        // Happend when user want to add a new product in category
        $("#NewFrontPageItemForm #addProductToCategory").click(function () {
            if (currentCategoryID > 0 && parseInt($("#newProductOption").attr("value")) > 0) {
                $.ajax({
                    type: "GET",
                    url: "/intranet/NewFrontPageProduct",
                    data: "optionid=" + $("#newProductOption").attr("value") +
                            "&category=" + currentCategoryID +
                            "&title=" + $("#EditNewProduct h3").html() +
                            "&description=" + $("#EditNewProduct .prod-description").html() +
                            "&position=" + $(".front-page-content #" + currentCategoryID + " .product").length,
                    success: function (msg) {
                        // check the return message and add new product into the list
                        if (msg > 0) {
                            var newHTML =
                            "<div class='product' id='option-" + msg + "'>" +
                            "<a href='#'><img src='" + $("#EditNewProduct .product .EditNewProductImage").attr("src") + "' alt=''/></a>" +
                                "<h3>" + $("#EditNewProduct h3").html() + "</h3>" +
                                "<p class='prod-description'>" + $("#EditNewProduct .prod-description").html() + "</p> " +
                                "<p class='prod-price'>" + $("#EditNewProduct .prod-price").html() + "</p> " +
                                "<p class='prod-delivery'>" + $("#EditNewProduct .prod-delivery").html() + "</p> " +
                            "<a href='#' onclick='FrontPageManagementV2.DeleteOption(" + msg + ")'><img src='/img/intranet/clickbut.gif' alt='' /></a></div>";
                            $(".front-page-content #" + currentCategoryID + " .categoryBarControl").before(newHTML);
                            // Assign the even to new object
                            $(".frontPageCategory #option-" + msg + " h3").editable(function (value, settings) {
                                SaveOptionChanges($(this).parent().attr("id").replace("option-", ""), "", value, "");
                                return value;
                            },
                            { submit: "Ok", cancel: 'Cancel' });

                            $(".frontPageCategory #option-" + msg + " .prod-description").editable(function (value, settings) {
                                SaveOptionChanges($(this).parent().attr("id").replace("option-", ""), "", "", value);
                                return value;
                            },
                            {
                                submit: "Ok", cancel: 'Cancel'
                            });
                            alert("New product added successfully");

                            $("#closeAddProduct2CatForm").click();
                        } else {
                            alert("Failed to create new product");
                        }
                    }
                });
            }
        });
        //$("#newProductOption").colorbox();
        // Assign editable for new product form
        $("#EditNewProduct h3").editable(function (value, settings) { return value; }, { submit: "Ok", cancel: 'Cancel' });
        $("#EditNewProduct .prod-description").editable(function (value, settings) { return value; }, { submit: "Ok", cancel: 'Cancel' });;
        // Assign editable for all product objects
        $(".frontPageCategory .product h3").editable(function (value, settings) {
            SaveOptionChanges($(this).parent().attr("id").replace("option-", ""), "", value, "");
            return value;
        },
            { submit: "Ok", cancel: 'Cancel' });

        $(".frontPageCategory .prod-description").editable(function (value, settings) {
            SaveOptionChanges($(this).parent().attr("id").replace("option-", ""), "", "", value);
            return value;
        },
            {
                submit: "Ok", cancel: 'Cancel'
            });
        // Assign editable for all category objects
        $(".front-page-content .frontPageCategory h2").editable(function (value, settings) {
            SaveCategoryChanges($(this).parent().attr("id"), value, "");
            return value;
        }, {
            submit: "Ok", cancel: "Cancel"
        });
        $(".front-page-content .frontPageCategory .cat-info").editable(function (value, settings) {
            SaveCategoryChanges($(this).parent().attr("id"), "", value);
            return value;
        }, {
            submit: "Ok", cancel: "Cancel"
        });
        // Init the form in the page
        InitForm("#NewFrontPageItemForm");
        InitForm("#ProductOptionSearchDiv");

        //display the controls if we want to
        var websiteId = $(".WebsiteSelect").val();
        if (websiteId != -1) {
            $(".categoryBarControl").show();
            $("#NewFrontPageCategoryForm").show();
        }
        $("#btnSearchProduct").click(function () {
            var SearchString = $("#txtProductSearchString").val();
            var StoreID = $("#ListStoreDropDown").val();
            var para = "/intranet/SearchProducts?StoreID=" + StoreID + "&SearchString=" + SearchString;
            var ajax = new ajaxObject(para);
            $("#ProductList").html(ajax.response());
        });
        $("#ProductExtraInformation").click(function (e) {
            if ($("#SelectedOptionInfo #hdProductId").val().length == 0) {
                alert("You will need to choose a product first");
            } else {
                $.fn.colorbox({ href: "/intranet/ProductInfo?productID=" + $("#SelectedOptionInfo #hdProductId").val(), open: true });
            }
            e.preventDefault();
        });
        },
        OpenFormAddNewProductToCategory: OpenFormAddNewProductToCategory,
        DeleteOption: DeleteOption,
        ReArrangeCategories: ReArrangeCategories,
        ReArrangeOptions: ReArrangeOptions,
        DeleteCategory: DeleteCategory,
        SelectedProductID:function () {
        return $("#SelectedOptionInfo #hdProductId").val();
},
SelectedProductName:function () {
    return $("#SelectedOptionInfo #SelectedProduct").html();
} ,        
SelectProduct: function (productID, ProductText) {
    
    $.ajax({
        type: "GET",
        url: "/intranet/GetProductOptions",
        data: "productId=" + productID,
        success: function (msg) {
            $("#ProductOptionList").html(msg);
        }
    });
    $("#hdProductId").val(productID);
    $("#hdProductOptionId").val("");
    $("#SelectedOption").html("");
    $("#SelectedProduct").html(ProductText);
},
SelectProductOption:function (optionID, OptionText) {
    $("#hdProductOptionId").val(optionID);
    $("#SelectedOption").html(OptionText);
}
    };
}();
var LeftMenuManagement = function () {
    function loadCategories(storeID) {
        $.ajax({
            type: "GET",
            data: "storeID=" + storeID,
            url: "/intranet/GetCategoriesList",
            success: function (msg) {
                $("#CategoryList").html(msg);
                $("#categories-list-ul").sortable({ item: "li" });
            }
        });
    }

    function leftCatCheckBoxChange(catID) {
        if ($("#cat-" + catID).attr("checked")) {
            $("#cat-" + catID).parent("li").insertAfter("#categories-list-ul .selectedLeftCat:last")
            $("#cat-" + catID).parent("li").addClass("selectedLeftCat");
            $("#cat-" + catID).parent("li").append("<input id='display-" + catID + "' class='displayTextBox' value='' />");
        } else {
            $("#cat-" + catID).parent("li").removeClass("selectedLeftCat");
            $("#display-" + catID).remove();
        }
    }


    return {
        //main function to initiate the theme
        init: function () {
            loadCategories($("#store-dropdown").val());
            // When user change the store
            $("#store-dropdown").change(function () {
                loadCategories($("#store-dropdown").val());
            });
            // When user reload the category
            $("#Reload-Category").click(function () {
                loadCategories($("#store-dropdown").val());
            });
            // When user click update button, it will save the information into the database using AJAX
            $("#Update-Category").click(function () {
                var selectedCatList = "";
                // Get the list of Checked Category ID
                $("#categories-list-ul input[type=checkbox]:checked").each(function () {
                    thisId = $(this).attr("id").replace("cat-", "");
                    selectedCatList += "|" + thisId + "¬" +($("#display-" + thisId).length>0?  $("#display-" + thisId).val():"");
                });
                selectedCatList = selectedCatList.substr(1, selectedCatList.length - 1); // Remove the first |
                // Send out the ajax
                $.ajax({
                    type: "GET",
                    data: "storeID=" + $("#store-dropdown").val() + "&catList=" + selectedCatList,
                    url: "/intranet/UpdateLeftMenuCategories",
                    success: function (msg) {
                        alert("Update successfully");
                        // relead the list when complete
                        loadCategories($("#store-dropdown").val());
                    },
                    fail: function (msg) {
                        alert("Sorry, Update process's failed. Please try again later");
                    }
                });
            });
        },
        leftCatCheckBoxChange: leftCatCheckBoxChange
    };
}();



var BannerManager = function () {
    var loadAjaxTypeSelected = function (objectid) {
        var type = $("#TypeList").val();
        var storeId = $( "#StoreID").val();
        if (type != "Home") {
            $.ajax({
                url: '/intranet/BannerGetTypeSelected',
                data: "storeId=" + storeId + "&type=" + type,
                success: function (data) {
                    $(".banner-row .typeSelected").remove();
                    $(".banner-row").append(data);
                    var catid = 0;
                    var proid = 0;
                    var catselected = $(document).find("#ddlCatSelected").html();
                    if (catselected != null) {
                        if (objectid != 0) {
                            $("#ddlCatSelected").val(objectid);
                        }
                        catid = $("#ddlCatSelected").val();
                    }
                    var prodselected = $(document).find("#ddlProdSelected").html();
                    if (prodselected != null) {
                        if (objectid != 0) {
                            $("#ddlProdSelected").val(objectid);
                        }
                        proid = $("#ddlProdSelected").val();

                    }
                    LoadAJAXBanner(catid, proid);
                    handleJs();
                }
            });
        }
    };

    var LoadAJAXBanner = function (catid, prodid) {
        var type = $("#TypeList").val();
        var storeId = $( "#StoreID").val();
        $.ajax({
            url: '/intranet/LoadBanner',
            data: "storeId=" + storeId + "&type=" + type + "&catid=" + catid + "&prodid=" + prodid,
            success: function (data) {
                $(".list-banner").html(data);
                shortbanner();
                $(".list-banner").sortable({
                    update: function (event, ui) {
                        $(".save-position").show();
                        shortbanner();
                    }
                });
                handleJs();
            }
        });
    };

    var shortbanner = function () {

        $(".list-banner #col1").removeClass("left");
        $(".list-banner #col1").each(function (e) {
            var index = $(this).index();
            if (index % 2 == 0) {
                $(this).addClass("left");
            }

        });
    };
    var handleJs = function () {
        $(".ddlCatSelected").change(function () {
            LoadAJAXBanner($(this).val(), 0);
        });
        $(".ddlProdSelected").change(function () {
            LoadAJAXBanner(0, $(this).val());
        });
        $("#fr-bannerupload").submit(function () {
            //grab all form data  
            var formData = new FormData($("#fr-bannerupload")[0]);
            $.ajax({
                url: '/intranet/bannerupload',
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    $('#imgBanner').attr("src", data);
                    $(".hidImageURL").val(data);
                },
                error: function () {
                }
            });
            return false;
        });

        $("#hf-storename").val($("#StoreID").text());
        $( "#StoreID").change(function () {
            var type = $(".ddlType").val();
            $("#hf-storename").val($(this).find("option:selected").text());
            var storeID = $(this).find("option:selected").val();
            if (type == "Category" && storeID > 0) {
                $(".hidCategoryID").val(0);
                ajaxLoadCategories();
            }
            else {
                if (type == "Product") {
                    $(".productId").val(0);
                    ajaxLoadProduct(0);
                    hideControl();
                }

            }

        });

        $(".delete-image").click(function () {
            if (confirm("Are you sure?")) {
                var image = $(".imgBanner").attr("src");
                $.ajax({
                    url: "/intranet/DeleteBannerImage",
                    data: "url=" + image,
                    success: function () {
                        $(".imgBanner").attr("src", "");
                    }
                });
            }
        });
        $(".btn-deletebanner").click(function () {
            var id = $(this).attr("rel");
            if (confirm("Are you sure?")) {
                $.ajax({
                    url: "/intranet/DeleteBanner",
                    data: "Id=" + id,
                    success: function () {
                        $(".banner-" + id).animate({ opacity: 0 }, 800, function () {
                            $(this).remove();
                        });
                    }
                });
            }
        });

        
    };
    var chooseControl = function () {
        // Hide View Product image when double click img
        $(".view-product img").click(function () {
            $(this).parent().hide();
            $("#view-product .view").parent().show();
            //$(".control-group .banner").append(" <div class='view-product' style='position:absolute; top : 0; left: 0;'><img id='imgViewProduct' runat='server' alt='View Product' src='/public/hieu/banner/assets/images/img-view-product.png'/></div>");
            $(".banner #view-product img.view").attr("src", "/img/img-view-product.png");
            moveImage();
            $(".hidViewProduct").val("left:0;top:0;");
        });

        // Hide Play Video image when double click img
        $(".play-video img").click(function () {
            $(".productId").val(0);
            ajaxLoadProduct(1);
            $(this).parent().hide();
            $("#play-video .play").parent().show();
            //$(".control-group .banner").append(" <div class='play-video' style='position:absolute; top : 0; left: 0;'><img id='imgPlayVideo' runat='server' alt='Play Video' src='/public/hieu/banner/assets/images/img-play-video.png'/></div>");
            $(".banner #play-video img.play").attr("src", "/img/img-play-video.png");
            moveImage();
            $(".hidPlayVideo").val("left:0;top:0;");
            $(".product-video").show();
        });
    };
    //
    var controlGroup = function () {
        //del button in image
        $(".del").click(function () {
            if (confirm("Are you sure?")) {
                $(this).next("img").attr("src", "/");
                var id = $(this).parent().attr("id");
                $("." + id).show();
                if (id == "play-video") {
                    $(".productList").slideUp();
                    $(".form-actions .productId").val(0);
                }
                $(this).parent().hide();
            }
            ;
        });

    };

    var hideControl = function () {
        $(".tool-box").hide();
        $("#play-video img.play").attr("src", "/");
        $("#view-product img.view").attr("src", "/");
        $("#play-video").hide();
        $("#view-product").hide();
    };

    //just show control when choose type is home or category
    var showControl = function () {
        // View img View-Product and img Play-Video
        if ($(".imgBanner").attr("src") != "") {
            // $(".box-container-toggle .box-content .img-content").css("display", "block");
            if ($(".ddlType").val() == "Product") {
                hideControl();
                return;
            }
            $(".tool-box").show();
            // Hide View Product Image
            if ($("#view-product img.view").attr("src") != "/") {
                $(".view-product").hide();
                moveImage();
            } else {
                $(".view-product").show();
            }

            // Hide Play Video Image
            if ($("#play-video img.play").attr("src") != "/") {
                $(".play-video").hide();
                moveImage();
            } else {
                $(".play-video").show();
            }
        }
    };
    var moveImage = function () {
        $("#view-product").draggable();
        $("#play-video").draggable();
        $(".banner").droppable({
            drop: function (event, ui) {
                setPosition();
            }
        });
    };
    var setPosition = function () {
        var leftView = 0;
        var topView = 0;
        var leftPlay = 0;
        var topPlay = 0;

        if ($(".banner #view-product img.view").attr("src") != "/") {
            var posView = $(".banner #view-product").position();
            leftView = parseInt(posView.left);
            topView = parseInt(posView.top);
            $(".hidViewProduct").val("left:" + leftView + "px; top:" + topView + "px;");
        } else {
            $(".hidViewProduct").val("");
        }
        if ($(".banner #play-video img.play").attr("src") != "/") {
            var posPlay = $(".banner #play-video").position();
            leftPlay = parseInt(posPlay.left);
            topPlay = parseInt(posPlay.top);
            $(".hidPlayVideo").val("left:" + leftPlay + "px; top:" + topPlay + "px;");

        } else {
            $(".hidPlayVideo").val("");
        }
    };

    //load ajax product for a product banner or product video
    function ajaxLoadProduct(video) {
        $(".loaddrop").css("display", "inline-block");
        var storeid = $( "#StoreID option:selected").val();
        if (video == 1) {
            $(".catList").slideDown();
        }
        else {
            $(".catList").slideUp();
        }
        $(".productList").slideDown();
        var productid = $(".productId").val();
        $.ajax({
            url: "/intranet/BannerGetProduct",
            data: "storeId=" + storeid + "&video=" + video,
            success: function (data) {
                $("#ddlProduct").html('');
                $.each(data, function (id, option) {
                    $("#ddlProduct").append($('<option></option>').val(option.id).html(option.name));
                });
                $(".loaddrop").hide();

                if (productid != 0) {
                    var catid = $(".hidCategoryID").val();
                    if (catid != 0)
                        $( ".ddlType").val("Category");
                    else
                        $( ".ddlType").val("Product");
                    $( ".ddlProduct").val(productid);
                    $(".productId").val(productid);
                }
                else {
                    $(".productId").val($( ".ddlProduct").val());
                }
                $(" #ddlProduct").change(function () {
                    var prodid = $(this).val();
                    $(".productId").val(prodid);
                    $(".product-video").show();
                    $(".product-name").val($(this).find("option:selected").text());
                });
            }
        });
    }

    var ajaxLoadCategories = function () {
        var store = $( "#StoreID").val();
        var catid = $(".hidCategoryID").val();
        $(".loaddrop").show();
        if ($(".banner #play-video img.play").attr("src") != "/") {
            $(".productList").slideDown();
            if ($(".productId").val() == "0" || $(".productId").val() == null)
                $(".productId").val(0);
            ajaxLoadProduct(1);
        } else {
            $(".productList").slideUp();
        }
        $(".catList").slideDown();

        $.ajax({
            url: '/intranet/BannerGetCategories',
            data: "storeId=" + store,
            success: function (data) {
                $(".catList").html(data);
                if (catid != 0) {
                    $( ".ddlType").val("Category");
                    $( ".ddlCategory").val(catid);
                    $(".hidCategoryID").val(catid);

                } else {
                    $(".hidCategoryID").val($( ".ddlCategory").val());
                }
                $( ".ddlCategory").change(function () {
                    $(".hidCategoryID").val($(this).val());
                });
                $(".loaddrop").hide();
            }
        });
    };

    var typeBanner = function () {
        var type = $(".ddlType option:selected").val();
        if (type == "Category") {
            ajaxLoadCategories();
        } else if (type == "Product") {
            hideControl();
            ajaxLoadProduct(0);
        }
        $( ".ddlType").change(function () {
            var type = $(this).val();
            if (type == "Category") {
                $(".productId").val(0);
                showControl();
                ajaxLoadCategories();
            } else {
                if (type != "Home") {
                    $(".productId").val(0);
                    $(".hidCategoryID").val(0);
                    ajaxLoadProduct(0);
                    hideControl();
                } else {
                    $(".hidCategoryID").val(0);
                    showControl();
                    $(".productList").slideUp();
                    $(".catList").slideUp();
                }
            }
            $(".product-video .product-name").val("");
        });
    };

    var saveBanner = function () {

        var store = $( "#StoreID").val();
        var type = $( ".ddlType").val();

        // close popup when click Cancel button
        $(".form-actions #btnCancel").click(function () {
            document.location.href = document.URL;

        });
        // Save into db
        $(".form-actions #btnSave").click(function () {
            store = $( "#StoreID ").val();
            type = $( ".ddlType").val();
            var ID = $(".hidBannerId").val();
            var title = $("#title").val();
            var link = $("#link").val();
            if (link.indexOf("#") != -1) {
                link = link.replace("#", "%23");
            }
            var prodId = $( ".ddlProduct").val();
            var category = $( ".ddlCategory").val();
            var imageURL = $(".control .imgBanner").attr("src");
            var viewProduct = $(".banner #view-product img.view").attr("src");
            var playVideo = $(".banner #play-video img.play").attr("src");
            var posView = $(".hidViewProduct").val();
            var posVideo = $(".hidPlayVideo").val();
            var startDate = $("#StartDate").val();
            var endDate = $("#EndDate").val();

            if (title == "") {
                $("#title").focus();
                $("#title").css("border-color", "#f70000");
            }else if (imageURL == "") {
                alert("Image not found");
            } else if (type == "Product" && (prodId == 0 || prodId == "")) {
                alert("Choose a product");
            } else if ($("#play-video img.play").attr("src") != "/" && (prodId == 0 || prodId == "" || prodId == undefined)) {
                alert("Choose a product to show video");
            } else {
                App.blockUI($('body'), false);
                $.ajax({
                    url: '/intranet/SaveBanner',
                    method: "POST",
                    data: "ID=" + ID + "&title=" + title + "&link=" + link + "&store=" + store +
                        "&type=" + type + "&category=" + category + "&imageURL=" + imageURL +
                        "&viewProduct=" + viewProduct + "&playVideo=" + playVideo +
                        "&posView=" + posView + "&posVideo=" + posVideo + "&prodId=" + prodId +
                        "&startDate=" + startDate + "&endDate=" + endDate,
                    success: function () {
                        alert("Save successful");
                        App.unblockUI($('body'));
                    },
                    error: function() {
                        alert('error!');
                        App.unblockUI($('body'));
                    }
                });
            }

        });
        var urlView = $("#view-product .view").attr("src");
        if (urlView == "/") {
            $("#view-product .view").parent().hide();
        }
        var urlPlay = $("#play-video .play").attr("src");
        if (urlPlay == "/") {
            $("#play-video .play").parent().hide();
        }
    };

    return {
        init: function () {
            //StoreList change load Image banner
            var type = $("#TypeList").val();
            if (type == "Home") {
                LoadAJAXBanner(0, 0);
            }
            else {
                loadAjaxTypeSelected(0);
            }

            $(".btnaddBanner").click(function (e) {
                e.preventDefault();
                BannerManager.bannerPopup(0);
            });

            $(".save-position").click(function () {
                App.blockUI($('body'), false);
                var position = "";
                $(".list-banner #col1").each(function () {
                    var id = $(this).find("#bannerid").val();
                    var index = $(this).index();
                    position += "|" + id + "," + index;
                });
                $.ajax({
                    url: "/intranet/BannerUpdatePosition",
                    data: "position=" + position,
                    success: function () {
                        alert("Save successful");
                        $(".save-position").hide();
                        App.unblockUI($('body'));
                    }
                });
            });
            handleJs();
            showControl();
            controlGroup();
            chooseControl();
            typeBanner();
            saveBanner();
        },
        typeChange: function () {
            var type = $("#TypeList").val();
            if (type != "Home") {
                loadAjaxTypeSelected(0);
            } else {
                $(".banner-row .typeSelected").remove();
                LoadAJAXBanner(0, 0);
            }
        },
        bannerPopup: function (bannerId) {
            var wPopup = $(document).width() / 10 * 8;
            var hPopup = $(window).height() / 10 * 9;
            var store = $( "#StoreID").val();
            var cate = 0;
            var prod = 0;
            var catselected = $(document).find("#ddlCatSelected").html();
            if (catselected != null) {
                cate = $("#ddlCatSelected").val();
            }
            var prodselected = $(document).find("#ddlProdSelected").html();
            if (prodselected != null) {
                prod = $("#ddlProdSelected").val();
            }
            var type = $("#TypeList").val();
            var url = "?";
            if (bannerId == 0) {
                url += "storeid=" + store + "&cateid=" + cate + "&prodid=" + prod + "&type=" + type;
            } else {
                url += "ID=" + bannerId;
            }
            triggerMacBox({
                boxID: "BannerPopup",
                borderType: "basic",
                width: wPopup,
                height: hPopup,
                source: "IFRAME",
                url: "/intranet/banner" + url,
                callback: function () {
                },
                onclose: function () {
                    var storeid = $(".ifr-macbox").contents().find( "#StoreID").val();
                    var type = $(".ifr-macbox").contents().find("#ddlType").val();
                    var catid = $(".ifr-macbox").contents().find( ".ddlCategory").val();
                    var prodid = $(".ifr-macbox").contents().find( ".ddlProduct").val();
                    $( "#StoreID").val(storeid);
                    $("#TypeList").val(type);
                    var objectid = 0;
                    if (type == "Category" && catid != null) {
                        objectid = catid;
                    } else if (type == "Product" && prodid != null) {
                        objectid = prodid;
                    } else {

                        LoadAJAXBanner(0, 0);
                    }
                    loadAjaxTypeSelected(objectid);
                    $("#BannerPopup").remove();

                }
            });
        },
        hidePopUp: function (id) {
            $("#txtproductname").val("");
            $("#over-popup").hide();
            var winw = $(window).width();
            var winpop = $(id).width();
            var left = (winw - winpop) / 2;
            $(id).stop().animate({ top: -999, left: left }, 500);
        },
        showPopUp: function (id, ctop) {
            $("#over-popup").show();
            var winw = $(window).width();
            var heiw = $(window).height();
            var winpop = $(id).width();
            var heipop = $(id).height();
            var top = (heiw - heipop) / 2 + $(window).scrollTop();
            if (ctop != null) {
                top = ctop;
            }
            var left = (winw - winpop) / 2;

            $(id).stop().animate({ top: top, left: left }, 500);
        }
    };
}();
